home *** CD-ROM | disk | FTP | other *** search
/ Die Speccy' 97 / Die Speccy' 97.iso / amiga_system / the_aminet / dev / lang / python020.lha / python / lib / pdb.py < prev    next >
Text File  |  1995-10-22  |  12KB  |  493 lines

  1. # pdb.py -- finally, a Python debugger!
  2.  
  3. # (See pdb.doc for documentation.)
  4.  
  5. import string
  6. import sys
  7. import linecache
  8. import cmd
  9. import bdb
  10. import repr
  11.  
  12.  
  13. # Interaction prompt line will separate file and call info from code
  14. # text using value of line_prefix string.  A newline and arrow may
  15. # be to your liking.  You can set it once pdb is imported using the
  16. # command "pdb.line_prefix = '\n% '".
  17. # line_prefix = ': '    # Use this to get the old situation back
  18. line_prefix = '\n-> '    # Probably a better default
  19.  
  20. class Pdb(bdb.Bdb, cmd.Cmd):
  21.     
  22.     def __init__(self):
  23.         bdb.Bdb.__init__(self)
  24.         cmd.Cmd.__init__(self)
  25.         self.prompt = '(Pdb) '
  26.     
  27.     def reset(self):
  28.         bdb.Bdb.reset(self)
  29.         self.forget()
  30.     
  31.     def forget(self):
  32.         self.lineno = None
  33.         self.stack = []
  34.         self.curindex = 0
  35.         self.curframe = None
  36.     
  37.     def setup(self, f, t):
  38.         self.forget()
  39.         self.stack, self.curindex = self.get_stack(f, t)
  40.         self.curframe = self.stack[self.curindex][0]
  41.     
  42.     # Override Bdb methods (except user_call, for now)
  43.     
  44.     def user_line(self, frame):
  45.         # This function is called when we stop or break at this line
  46.         self.interaction(frame, None)
  47.     
  48.     def user_return(self, frame, return_value):
  49.         # This function is called when a return trap is set here
  50.         frame.f_locals['__return__'] = return_value
  51.         print '--Return--'
  52.         self.interaction(frame, None)
  53.     
  54.     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
  55.         # This function is called if an exception occurs,
  56.         # but only if we are to stop at or just below this level
  57.         frame.f_locals['__exception__'] = exc_type, exc_value
  58.         if type(exc_type) == type(''):
  59.             exc_type_name = exc_type
  60.         else: exc_type_name = exc_type.__name__
  61.         print exc_type_name + ':', repr.repr(exc_value)
  62.         self.interaction(frame, exc_traceback)
  63.     
  64.     # General interaction function
  65.     
  66.     def interaction(self, frame, traceback):
  67.         self.setup(frame, traceback)
  68.         self.print_stack_entry(self.stack[self.curindex])
  69.         self.cmdloop()
  70.         self.forget()
  71.  
  72.     def default(self, line):
  73.         if line[:1] == '!': line = line[1:]
  74.         locals = self.curframe.f_locals
  75.         globals = self.curframe.f_globals
  76.         globals['__privileged__'] = 1
  77.         code = compile(line + '\n', '<stdin>', 'single')
  78.         try:
  79.             exec code in globals, locals
  80.         except:
  81.             if type(sys.exc_type) == type(''):
  82.                 exc_type_name = sys.exc_type
  83.             else: exc_type_name = sys.exc_type.__name__
  84.             print '***', exc_type_name + ':', sys.exc_value
  85.  
  86.     # Command definitions, called by cmdloop()
  87.     # The argument is the remaining string on the command line
  88.     # Return true to exit from the command loop 
  89.     
  90.     do_h = cmd.Cmd.do_help
  91.  
  92.     def do_break(self, arg):
  93.         if not arg:
  94.             print self.get_all_breaks() # XXX
  95.             return
  96.         # Try line number as argument
  97.         try:    
  98.             lineno = int(eval(arg))
  99.             filename = self.curframe.f_code.co_filename
  100.         except:
  101.             # Try function name as the argument
  102.             import codehack
  103.             try:
  104.                 func = eval(arg, self.curframe.f_globals,
  105.                         self.curframe.f_locals)
  106.                 if hasattr(func, 'im_func'):
  107.                     func = func.im_func
  108.                 code = func.func_code
  109.             except:
  110.                 print '*** Could not eval argument:', arg
  111.                 return
  112.             lineno = codehack.getlineno(code)
  113.             filename = code.co_filename
  114.  
  115.         # now set the break point
  116.         err = self.set_break(filename, lineno)
  117.         if err: print '***', err
  118.     do_b = do_break
  119.     
  120.     def do_clear(self, arg):
  121.         if not arg:
  122.             try:
  123.                 reply = raw_input('Clear all breaks? ')
  124.             except EOFError:
  125.                 reply = 'no'
  126.             reply = string.lower(string.strip(reply))
  127.             if reply in ('y', 'yes'):
  128.                 self.clear_all_breaks()
  129.             return
  130.         try:
  131.             lineno = int(eval(arg))
  132.         except:
  133.             print '*** Error in argument:', `arg`
  134.             return
  135.         filename = self.curframe.f_code.co_filename
  136.         err = self.clear_break(filename, lineno)
  137.         if err: print '***', err
  138.     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
  139.     
  140.     def do_where(self, arg):
  141.         self.print_stack_trace()
  142.     do_w = do_where
  143.     
  144.     def do_up(self, arg):
  145.         if self.curindex == 0:
  146.             print '*** Oldest frame'
  147.         else:
  148.             self.curindex = self.curindex - 1
  149.             self.curframe = self.stack[self.curindex][0]
  150.             self.print_stack_entry(self.stack[self.curindex])
  151.             self.lineno = None
  152.     do_u = do_up
  153.     
  154.     def do_down(self, arg):
  155.         if self.curindex + 1 == len(self.stack):
  156.             print '*** Newest frame'
  157.         else:
  158.             self.curindex = self.curindex + 1
  159.             self.curframe = self.stack[self.curindex][0]
  160.             self.print_stack_entry(self.stack[self.curindex])
  161.             self.lineno = None
  162.     do_d = do_down
  163.     
  164.     def do_step(self, arg):
  165.         self.set_step()
  166.         return 1
  167.     do_s = do_step
  168.     
  169.     def do_next(self, arg):
  170.         self.set_next(self.curframe)
  171.         return 1
  172.     do_n = do_next
  173.     
  174.     def do_return(self, arg):
  175.         self.set_return(self.curframe)
  176.         return 1
  177.     do_r = do_return
  178.     
  179.     def do_continue(self, arg):
  180.         self.set_continue()
  181.         return 1
  182.     do_c = do_cont = do_continue
  183.     
  184.     def do_quit(self, arg):
  185.         self.set_quit()
  186.         return 1
  187.     do_q = do_quit
  188.     
  189.     def do_args(self, arg):
  190.         if self.curframe.f_locals.has_key('__args__'):
  191.             print `self.curframe.f_locals['__args__']`
  192.         else:
  193.             print '*** No arguments?!'
  194.     do_a = do_args
  195.     
  196.     def do_retval(self, arg):
  197.         if self.curframe.f_locals.has_key('__return__'):
  198.             print self.curframe.f_locals['__return__']
  199.         else:
  200.             print '*** Not yet returned!'
  201.     do_rv = do_retval
  202.     
  203.     def do_p(self, arg):
  204.         self.curframe.f_globals['__privileged__'] = 1
  205.         try:
  206.             value = eval(arg, self.curframe.f_globals, \
  207.                     self.curframe.f_locals)
  208.         except:
  209.             if type(sys.exc_type) == type(''):
  210.                 exc_type_name = sys.exc_type
  211.             else: exc_type_name = sys.exc_type.__name__
  212.             print '***', exc_type_name + ':', `sys.exc_value`
  213.             return
  214.  
  215.         print `value`
  216.  
  217.     def do_list(self, arg):
  218.         self.lastcmd = 'list'
  219.         last = None
  220.         if arg:
  221.             try:
  222.                 x = eval(arg, {}, {})
  223.                 if type(x) == type(()):
  224.                     first, last = x
  225.                     first = int(first)
  226.                     last = int(last)
  227.                     if last < first:
  228.                         # Assume it's a count
  229.                         last = first + last
  230.                 else:
  231.                     first = max(1, int(x) - 5)
  232.             except:
  233.                 print '*** Error in argument:', `arg`
  234.                 return
  235.         elif self.lineno is None:
  236.             first = max(1, self.curframe.f_lineno - 5)
  237.         else:
  238.             first = self.lineno + 1
  239.         if last == None:
  240.             last = first + 10
  241.         filename = self.curframe.f_code.co_filename
  242.         breaklist = self.get_file_breaks(filename)
  243.         try:
  244.             for lineno in range(first, last+1):
  245.                 line = linecache.getline(filename, lineno)
  246.                 if not line:
  247.                     print '[EOF]'
  248.                     break
  249.                 else:
  250.                     s = string.rjust(`lineno`, 3)
  251.                     if len(s) < 4: s = s + ' '
  252.                     if lineno in breaklist: s = s + 'B'
  253.                     else: s = s + ' '
  254.                     if lineno == self.curframe.f_lineno:
  255.                         s = s + '->'
  256.                     print s + '\t' + line,
  257.                     self.lineno = lineno
  258.         except KeyboardInterrupt:
  259.             pass
  260.     do_l = do_list
  261.  
  262.     def do_whatis(self, arg):
  263.         try:
  264.             value = eval(arg, self.curframe.f_globals, \
  265.                     self.curframe.f_locals)
  266.         except:
  267.             if type(sys.exc_type) == type(''):
  268.                 exc_type_name = sys.exc_type
  269.             else: exc_type_name = sys.exc_type.__name__
  270.             print '***', exc_type_name + ':', `sys.exc_value`
  271.             return
  272.         code = None
  273.         # Is it a function?
  274.         try: code = value.func_code
  275.         except: pass
  276.         if code:
  277.             print 'Function', code.co_name
  278.             return
  279.         # Is it an instance method?
  280.         try: code = value.im_func.func_code
  281.         except: pass
  282.         if code:
  283.             print 'Method', code.co_name
  284.             return
  285.         # None of the above...
  286.         print type(value)
  287.     
  288.     # Print a traceback starting at the top stack frame.
  289.     # The most recently entered frame is printed last;
  290.     # this is different from dbx and gdb, but consistent with
  291.     # the Python interpreter's stack trace.
  292.     # It is also consistent with the up/down commands (which are
  293.     # compatible with dbx and gdb: up moves towards 'main()'
  294.     # and down moves towards the most recent stack frame).
  295.     
  296.     def print_stack_trace(self):
  297.         try:
  298.             for frame_lineno in self.stack:
  299.                 self.print_stack_entry(frame_lineno)
  300.         except KeyboardInterrupt:
  301.             pass
  302.     
  303.     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
  304.         frame, lineno = frame_lineno
  305.         if frame is self.curframe:
  306.             print '>',
  307.         else:
  308.             print ' ',
  309.         print self.format_stack_entry(frame_lineno, prompt_prefix)
  310.  
  311.  
  312.     # Help methods (derived from pdb.doc)
  313.  
  314.     def help_help(self):
  315.         self.help_h()
  316.  
  317.     def help_h(self):
  318.         print """h(elp)
  319.     Without argument, print the list of available commands.
  320.     With a command name as argument, print help about that command
  321.     "help pdb" pipes the full documentation file to the $PAGER
  322.     "help exec" gives help on the ! command"""
  323.  
  324.     def help_where(self):
  325.         self.help_w()
  326.  
  327.     def help_w(self):
  328.         print """w(here)
  329.     Print a stack trace, with the most recent frame at the bottom.
  330.     An arrow indicates the "current frame", which determines the
  331.     context of most commands."""
  332.  
  333.     def help_down(self):
  334.         self.help_d()
  335.  
  336.     def help_d(self):
  337.         print """d(own)
  338.     Move the current frame one level down in the stack trace
  339.     (to an older frame)."""
  340.  
  341.     def help_up(self):
  342.         self.help_u()
  343.  
  344.     def help_u(self):
  345.         print """u(p)
  346.     Move the current frame one level up in the stack trace
  347.     (to a newer frame)."""
  348.  
  349.     def help_break(self):
  350.         self.help_b()
  351.  
  352.     def help_b(self):
  353.         print """b(reak) [lineno | function]
  354.     With a line number argument, set a break there in the current
  355.     file.  With a function name, set a break at the entry of that
  356.     function.  Without argument, list all breaks."""
  357.  
  358.     def help_clear(self):
  359.         self.help_cl()
  360.  
  361.     def help_cl(self):
  362.         print """cl(ear) [lineno]
  363.     With a line number argument, clear that break in the current file.
  364.     Without argument, clear all breaks (but first ask confirmation)."""
  365.  
  366.     def help_step(self):
  367.         self.help_s()
  368.  
  369.     def help_s(self):
  370.         print """s(tep)
  371.     Execute the current line, stop at the first possible occasion
  372.     (either in a function that is called or in the current function)."""
  373.  
  374.     def help_next(self):
  375.         self.help_n()
  376.  
  377.     def help_n(self):
  378.         print """n(ext)
  379.     Continue execution until the next line in the current function
  380.     is reached or it returns."""
  381.  
  382.     def help_return(self):
  383.         self.help_r()
  384.  
  385.     def help_r(self):
  386.         print """r(eturn)
  387.     Continue execution until the current function returns."""
  388.  
  389.     def help_continue(self):
  390.         self.help_c()
  391.  
  392.     def help_cont(self):
  393.         self.help_c()
  394.  
  395.     def help_c(self):
  396.         print """c(ont(inue))
  397.     Continue execution, only stop when a breakpoint is encountered."""
  398.  
  399.     def help_list(self):
  400.         self.help_l()
  401.  
  402.     def help_l(self):
  403.         print """l(ist) [first [,last]]
  404.     List source code for the current file.
  405.     Without arguments, list 11 lines around the current line
  406.     or continue the previous listing.
  407.     With one argument, list 11 lines starting at that line.
  408.     With two arguments, list the given range;
  409.     if the second argument is less than the first, it is a count."""
  410.  
  411.     def help_args(self):
  412.         self.help_a()
  413.  
  414.     def help_a(self):
  415.         print """a(rgs)
  416.     Print the argument list of the current function."""
  417.  
  418.     def help_p(self):
  419.         print """p expression
  420.     Print the value of the expression."""
  421.  
  422.     def help_exec(self):
  423.         print """(!) statement
  424.     Execute the (one-line) statement in the context of
  425.     the current stack frame.
  426.     The exclamation point can be omitted unless the first word
  427.     of the statement resembles a debugger command.
  428.     To assign to a global variable you must always prefix the
  429.     command with a 'global' command, e.g.:
  430.     (Pdb) global list_options; list_options = ['-l']
  431.     (Pdb)"""
  432.  
  433.     def help_quit(self):
  434.         self.help_q()
  435.  
  436.     def help_q(self):
  437.         print """q(uit)    Quit from the debugger.
  438.     The program being executed is aborted."""
  439.  
  440.     def help_pdb(self):
  441.         help()
  442.  
  443. # Simplified interface
  444.  
  445. def run(statement, globals=None, locals=None):
  446.     Pdb().run(statement, globals, locals)
  447.  
  448. def runeval(expression, globals=None, locals=None):
  449.     return Pdb().runeval(expression, globals, locals)
  450.  
  451. def runctx(statement, globals, locals):
  452.     # B/W compatibility
  453.     run(statement, globals, locals)
  454.  
  455. def runcall(*args):
  456.     return apply(Pdb().runcall, args)
  457.  
  458. def set_trace():
  459.     Pdb().set_trace()
  460.  
  461. # Post-Mortem interface
  462.  
  463. def post_mortem(t):
  464.     p = Pdb()
  465.     p.reset()
  466.     while t.tb_next <> None: t = t.tb_next
  467.     p.interaction(t.tb_frame, t)
  468.  
  469. def pm():
  470.     import sys
  471.     post_mortem(sys.last_traceback)
  472.  
  473.  
  474. # Main program for testing
  475.  
  476. TESTCMD = 'import x; x.main()'
  477.  
  478. def test():
  479.     run(TESTCMD)
  480.  
  481. # print help
  482. def help():
  483.     import os
  484.     for dirname in sys.path:
  485.         fullname = os.path.join(dirname, 'pdb.doc')
  486.         if os.path.exists(fullname):
  487.             sts = os.system('${PAGER-more} '+fullname)
  488.             if sts: print '*** Pager exit status:', sts
  489.             break
  490.     else:
  491.         print 'Sorry, can\'t find the help file "pdb.doc"',
  492.         print 'along the Python search path'
  493.